package test.re;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import test.dom.Test4;

import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ReTest4 {

    public static void main(String[] args) throws Exception {

        SAXReader saxReader = new SAXReader();

        // 获取资源路径并进行URL解码
        String path = Test4.class.getClassLoader().getResource("test3.xml").getPath();
        String decodedPath = URLDecoder.decode(path, StandardCharsets.UTF_8.name());
        Document doc = saxReader.read(decodedPath);

        //key: 完全类名 value: 对象
        HashMap<String,Object> objectHashMap = new HashMap<>();

        for (Node node1: doc.selectNodes("//method")) {
            Element elementNode = (Element) node1;
            String methodName = elementNode.attributeValue("name");
            String className = elementNode.attributeValue("class");
            Object obj = null;
            if(objectHashMap.containsKey(className)){
                obj = objectHashMap.get(className);
            }else{
                Class clz = Class.forName(className);
                obj = clz.newInstance();
                objectHashMap.put(className,obj);
            }


            List<Class> classes = new ArrayList<>();
            List<Object> params = new ArrayList<>();
            List<Element> elementList = elementNode.elements("param");

            //获取参数列表
            for (int i = 0; i < elementList.size(); i++){
                Element elementParam = elementList.get(i);
                String type = elementParam.attributeValue("type");
                String value = elementParam.attributeValue("value");

                classes.add(getClass(type));
                params.add(getValue(value,classes.get(i)));
            }
            Method method = obj.getClass().getDeclaredMethod(methodName, classes.toArray(new Class[0]));
            method.invoke(obj,params.toArray());
        }
    }

    private static Object getValue(String value,Class clz){
        if(clz == int.class){
            return Integer.parseInt(value);
        }else if(clz == String.class){
            return value;
        }else{
            return value;
        }
    }

    private static Class getClass(String type){
        if(type.equals("int")){
            return int.class;
        }else if(type.equals("String")){
            return String.class;
        }
        return Object.class;
    }
}
